package org.qloudgen.borg.pages;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.validation.validator.StringValidator;
import org.qloudgen.borg.CommonValues;
import org.qloudgen.borg.beans.UserBean;
import org.qloudgen.borg.metadb.DefaultImpl;
import org.qloudgen.borg.pages.common.BasePage;

import com.google.common.collect.Lists;

@SuppressWarnings("rawtypes")
public class UserCreatePage extends BasePage{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@SuppressWarnings("unchecked")
	public UserCreatePage(){
		
		super();
		
		Form form = new Form("form",new CompoundPropertyModel<UserBean>(new UserBean().setTaskNumber(CommonValues.DEFAULT_USER_TASK_NUMBER))){
			
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit() {
				
				UserBean user = (UserBean) getDefaultModelObject();
				
				if (DefaultImpl.isExistsUser(user.getUserNo()) != null) {
					error(CommonValues.ERROR_CREATE_USER);
				} else {
					if (user.getTaskNumber() == 0 ) 
						user.setTaskNumber(CommonValues.DEFAULT_USER_TASK_NUMBER);
					
					user.setUserPassword(CommonValues.DEFAULT_USER_PASSWORD);
					user.setUserStatus(CommonValues.STATUS_NORMAL);
					DefaultImpl.createUser(user);
					setResponsePage(UserListPage.class);
				}
			}
		};
		form.setOutputMarkupId(true);
		add(form);
		
		RequiredTextField<String> userNo = new RequiredTextField<String>("userNo");
		userNo.add(StringValidator.minimumLength(4));
		form.add(userNo);
		
		form.add(new RequiredTextField<String>("userName"));
		
		IChoiceRenderer<Object> renderer = new ChoiceRenderer<Object>() {
			private static final long serialVersionUID = 1L;
			public Object getDisplayValue(Object object) {
				return CommonValues.userTypeNames.get(object);
			}
		};
		
		DropDownChoice<String> userType = new DropDownChoice<String>("userType",Lists.newArrayList(CommonValues.userTypeNames.keySet()),renderer);
		userType.setRequired(true);
		form.add(userType);

		form.add(new RequiredTextField<String>("taskNumber"));
		
		form.add(new Button("submit"));
		
		Button cancel = new Button ("cancel"){
			private static final long serialVersionUID = 1L;
			public void onSubmit() {
				setResponsePage(UserListPage.class);
			}
		};
		form.add(cancel);
		cancel.setDefaultFormProcessing(false);
	}
	
}